import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home'
import User from '../views/User'
import Main from '../views/Main'
import Mall from '../views/Mall'
import PageOne from '../views/PageOne'
import PageTwo from '../views/PageTwo'
import Login from '../views/Login'
//引入Cookie
import Cookie from 'js-cookie'

Vue.use(VueRouter)

//1.创建路由组件
//2.将路由和组件进行映射
//3.创建router实例
//4.嵌套路由

const routes = [
  // 主路由
  {
    path: '/',
    component: Main,
    name:'Main',
    redirect: '/home',//重定向
    children: [
      //子路由
      /* { path: 'home', name: 'home', component: Home },//首页
      { path: 'user', name: 'user', component: User },//用户管理
      { path: 'mall', name: 'mall', component: Mall },//商品管理
      { path: 'Page1', name: 'Page1', component: PageOne },//页面1
      { path: 'Page2', name: 'Page2', component: PageTwo } //页面2 */
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  }
]



const router = new VueRouter({
  routes
})

//添加全局前置导航守卫
router.beforeEach((to, from, next) => {
  //判断token存不存在
  const token = Cookie.get('token')
  if (!token && to.name !== 'login') { //判断token是否存在
    //不存在,当前用户未登录,应该跳转到登录页
    next({ name: 'login' })
  } else if (token && to.name === 'login') {//token存在,说明用户登陆,此时跳转至首页
    next({ name: 'home' })
  } else {
    next()
  }
})

export default router